package com.totoro.utils;


import com.sun.mail.util.MailSSLSocketFactory;
import com.totoro.view.EmailHtml;
import lombok.experimental.UtilityClass;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.util.Properties;

/**
 * 发送邮件工具
 * ps:该工具使用QQ邮箱发送给他人，使用前需要在自己的QQ邮箱当中设置开启POP3/SMTP服务，并获取一次授权码进行使用。
 * @author TOTORO
 * @date 2021/5/11 11:29
 */
@UtilityClass
public class MailUtil {
    private static boolean flag = true;
    /** 发件人电子邮箱 */
    private static final String from = "totoro.yc@qq.com";
    /** 发件人授权码(上述) */
    private static final String authorizeCode = "dbdxbhmdcuibicei";
    /** 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易) */
    private static final String host = "smtp.qq.com";


    /**
     *
     * @param email [邮箱用户]
     * @param random [注册邮箱随机数判断码]
     * @param type [邮箱发送类型]
     * @param url [发送给用户的点击地址]
     * @throws MessagingException
     */
    public static void sendMail(String email, String random, int type, String url) throws MessagingException {
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        // 打开认证
        properties.setProperty("mail.smtp.auth", "true");

        try {
            //QQ邮箱需要下面这段代码，163邮箱不需要
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            properties.put("mail.smtp.ssl.enable", "true");
            properties.put("mail.smtp.ssl.socketFactory", sf);


            // 1.获取默认session对象
            Session session = Session.getDefaultInstance(properties, new Authenticator() {
                @Override
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication("totoro.yc@qq.com", "dbdxbhmdcuibicei"); // 发件人邮箱账号、授权码
                }
            });

            // 2.创建邮件对象
            Message message = new MimeMessage(session);
            // 2.1设置发件人
            message.setFrom(new InternetAddress(from));
            // 2.2设置接收人
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
            // 2.3设置邮件主题
            message.setSubject("天猫邮箱验证(系统邮件，请勿回复)");
            if(type==1){
                message.setContent(EmailHtml.getRegisterHtml(email, random), "text/html;charset=UTF-8");
            } else{
                message.setContent(EmailHtml.getFindPasswordHtml(url), "text/html;charset=UTF-8");
            }
            // 3.发送邮件
            Transport.send(message);
            System.out.println("邮件成功发送!");
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            flag = false;
        }
    }
    public static boolean isFlag() {
        return flag;
    }
    public static void setFlag(boolean flag) {
        MailUtil.flag = flag;
    }

}
